import Vue from 'vue'	//引入vue
import VueRouter from 'vue-router'	//引入vue-router模块
// 引入进度条组件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import  store from '@/store/store'
NProgress.configure({ showSpinner: false })

Vue.use(VueRouter)	//声明安装路由
const routes  =   [
  {name:'首页',path:'/',redirect: '/index'},
  {name:'首页',path:"/index",component:()=> import ('@/pages/index/index'),},//主页
	{name:'demo',path:"/demo",component:()=> import ('@/pages/demo/demo'),meta:{requireAuth:true}},//主页
  {name:'login',path:"/login",component:()=> import ('@/pages/login/login')},
]
const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
// 添加路由守卫
router.beforeEach((to, from, next) => {
  document.title = to.name ? to.name : '玉丹颜'
      if (to.meta.requireAuth) {     // 判断该路由是否需要登录权限
          let token = store.state.token||localStorage.getItem('token'); 
          console.log(token ,"去登录",to.meta.requireAuth)
          if (!token){// 通过localStorage.getItem()获取当前的 token 是否存在
              if(from.query.redirect==to.fullPath)return;
              router.push({path:'/login',query: {
                  redirect: to.fullPath    // 将跳转的路由path作为参数，登录成功后跳转到该路由
              }})
          }else{
              next()
          }
      }else{
          next()
      }
})
// 后置路由守卫
router.afterEach((to, from) => {
  NProgress.done();
})

export default  router